<!--
 @Author: libing/makeup1122
 @Email: makeup1123@163.com
 @Date: "2020-03-07 15:37:31"
-->
<template>
  <v-form ref="materialForm">
  <v-file-input
    :loading="loading"
    :label="label"
    :accept="accept"
    v-model="file"
    show-size
    :rules="rules"
    @change="changeHandle"></v-file-input>
    </v-form>
</template>
<script>
import { postMaterial } from '@/api/attachment.js'
export default {
  name: 'WxMaterialUpload',
  components: {},
  props: {
    type: String,
    filename: String,
    filepath: String,
    fileurl: String,
    filehash: String,
    title: String,
    label: {
      type: String,
      default: '上传'
    }
  },
  data: function () {
    return {
      file: null,
      loading: false
    }
  },
  created: function () {
  },
  computed: {
    rules: function() {
      switch (this.type) {
        case 'image':
          return [
            value => !value || value.size < 2000000 || '图片大小不能超过 2 MB!'
          ]
        case 'audio':
          return [
            value => !value || value.size < 2000000 || '语音文件大小不能超过 2 MB，播放长度不超过60s！'
          ]
        case 'video':
          return [
            value => !value || value.size < 10000000 || '视频大小不能超过 10 MB!'
          ]
        case 'thumb':
          return [
            value => !value || value.size < 64000 || '缩略图大小不能超过64KB!'
          ]
        default:
          return []
      }
    },
    accept: function() {
      switch (this.type) {
        case 'image':
          return '.bmp,.png,.jpeg,.jpg,.gif'
        case 'video':
          return '.mp4'
        case 'audio':
          return '.mp3,.wma,.wav,.amr'
        case 'thumb':
          return '.jpg'
        default:
          return '*/*'
      }
    }
  },
  methods: {
    changeHandle(file) {
      this.$validator.validate().then(result => {
        if (result) {
          if (typeof file === 'object') {
            this.loading = true
            postMaterial(file, 'material').then(res => {
              this.$emit('update:filepath', res.data.filepath)
              this.$emit('update:filename', res.data.filename)
              this.$emit('update:fileurl', res.data.url)
              this.$emit('update:filehash', res.data.hash)
              this.$emit('update:title', res.data.filename)
            }).finally(() => {
              this.loading = false
            })
          }
        }
      })
    }
  }
}
</script>
<style scoped>
</style>
